<?php
/**
 * KePHP, Keep PHP easy!
 */

namespace Gitee\Controller;

use Gitee\GiteeAPI\AppAPI;
use Gitee\GiteeAppApi;
use Ke\Uri;
use Ke\Web\Controller;

class Index extends Controller
{
	
	protected $sessionName = 'gitee_sess';
	
	protected $giteeAppName = 'gitee-app';
	
	public $layout = 'default';
	
	/** @var \Gitee\GiteeAPI\AppAPI */
	public $giteeApi;
	
	/** @var \Gitee\Db\Gitee\App */
	public $giteeApp;
	
	/** @var \Gitee\Db\Gitee\App_Token */
	public $giteeToken;
	
	protected function onConstruct()
	{
		session_name($this->sessionName);
		session_start();
		$this->giteeApi = new AppAPI($this->giteeAppName);
		$this->giteeApp = $this->giteeApi->app();
		$this->giteeToken = $this->giteeApp->getSessionToken();
		
		if (!$this->giteeToken->isValid($this->giteeApp)) {
			if ($this->isRequireAuth()) {
				$this->markRefRedirect($this->giteeApi->getVerifyUri());
				exit();
			}
		}
	}
	
	protected function isRequireAuth()
	{
		$currentController = $this->web->filterController(get_class($this));
		if ($this->web->isController($currentController) && $this->web->isAction('login')) {
			return false;
		}
		return true;
	}
	
	protected function markRefRedirect($gotoUri)
	{
		$_SESSION['ref_url'] = Uri::current()->toUri(true);
		return $this->redirect($gotoUri);
	}
	
	protected function redirectRef($orGotoUri = null)
	{
		$uri = $_SESSION['ref_url'] ?? $orGotoUri ?? $this->web->controllerLink('');
		if (isset($_SESSION['ref_url'])) {
			unset($_SESSION['ref_url']);
		}
		return $this->redirect($uri);
	}
	
	public function index()
	{
	}
	
	public function login()
	{
		$code = $this->http->query('code');
		if (!empty($code)) {
			$token = $this->giteeApi->reqToken($code);
			if ($this->giteeApi->app()->saveToken($token)->isSuccess()) {
				return $this->redirectRef($this->web->controllerLink(''));
			}
		}
	}
}